package com.zhb.blog.service;

import com.zhb.blog.NotFoundException;
import com.zhb.blog.dao.BlogRepository;
import com.zhb.blog.dao.CommentRepository;
import com.zhb.blog.model.Blog;
import com.zhb.blog.util.MarkDownUtils;
import com.zhb.blog.util.MyBeanUtils;
import com.zhb.blog.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;


@Service
public class BlogServiceImpl implements BlogService {
    @Autowired
    BlogRepository blogRepository;
    @Autowired
    CommentRepository commentRepository;

    @Override
    public Blog getBlog(Long id) {
        return blogRepository.findById(id).orElseThrow(() ->new NotFoundException("没有找到编号为"+id+"的博客"));
    }
    @Transactional
    @Override
    public Blog getAndConvert(Long id) {
        Blog blog = blogRepository.findById(id).orElseThrow(() ->new NotFoundException("没有找到编号为"+id+"的博客"));
        if(blog == null){
            throw new NotFoundException("该博客不存在");
        }
        Blog b = new Blog();
        BeanUtils.copyProperties(blog,b);
        String content = b.getContent();
        b.setContent(MarkDownUtils.markdownToHtmlExtensions(content));
        blogRepository.updateViews(id);//更新浏览次数
        return b;
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                //设定根据标题模糊查询
                if(!"".equals(blog.getTitle()) && blog.getTitle() != null){
                    predicates.add(cb.like(root.<String>get("title"),"%"+blog.getTitle()+"%"));
                }
                //设定根据标签精准查询
                if(blog.getTypeId() != null){
                    predicates.add(cb.equal(root.<String>get("type").get("id"),blog.getTypeId()));
                }
                //设定根据是否推荐查询
                if(blog.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommend"),blog.isRecommend()));
                }
                //开始查询
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {

        return blogRepository.findPublishedBlog(pageable);
    }

    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {

        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                //关联查询
                Join join = root.join("tags");

                return cb.equal(join.get("id"),tagId);
            }
        },pageable);
    }

    @Override
    public Page<Blog> listBlog(String query,Pageable pageable) {


        return blogRepository.findByQuery(query,pageable);
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        PageRequest of = PageRequest.of(0, size, sort);
        return blogRepository.findTop(of);
    }

    @Override
    public Map<String, List<Blog>> archiveBlog() {
        List<String> years = blogRepository.findGroupYear();
        Map<String,List<Blog>> map = new HashMap<>();
        for(String year : years){
            map.put(year,blogRepository.findByYear(year));
        }
        List<String> nullBlogYears = new ArrayList<>();//存储发布的博客为空的年份
        for(Map.Entry<String, List<Blog>> entry : map.entrySet()){
            //如果对应的年份下没有已发布的博客，那么将其从Map中删除
            if(entry.getValue().size()==0){
                //由于用这种迭代的方式不能操作map，所以先将要删除的元素key存入List中，之后再根据keys进行删除
                System.out.println(entry.getKey());
                nullBlogYears.add(entry.getKey());
            }
        }
        for(int i=0;i<nullBlogYears.size();i++){
            map.remove(nullBlogYears.get(i));
        }

        return map;
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
//        if(blog.getId() == null){
//            //新增
//            blog.setCreateTime(new Date());
//            blog.setUpdateTime(new Date());
//            blog.setViews(0);//浏览次数
//        }else{
//            //修改
//            blog.setUpdateTime(new Date());
//        }
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blog.setViews(0);//浏览次数

        return blogRepository.save(blog);
    }
    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog b = blogRepository.findById(id).orElseThrow(() ->new NotFoundException("没有找到编号为"+id+"的分类"));

        //将blog中值不为空的属性copy到b中，过滤掉那些值为空的属性
        BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdateTime(new Date());
        return blogRepository.save(b);
    }
    @Transactional
    @Override
    public void deleteBlog(Long id) {
        commentRepository.deleteByBlogId(id);
        blogRepository.deleteById(id);
    }

    @Override
    public Long countBlog() {
        return blogRepository.count();
    }

}
